package com.ahstu.learning.leftMenu;
//学习调用有道词典的翻译效果  来进行语句的翻译

import android.content.Context;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.ahstu.learning.base.BaseActivity;
import com.ahstu.learning.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class TranslationActivity extends BaseActivity {

    private final static int JIAZAI_OK = 0;//表示数据加载成功

    private android.os.Handler handler = new android.os.Handler() {
        public void handleMessage(android.os.Message msg) {
            //主线程里面接受消息的机制
            switch (msg.what) {

                case JIAZAI_OK://表示加载成功
                    //现在是应该显示数据
                    try {
                        setShuJu();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }//现在应该来显示数据

            }
        }

        ;


    };
    private EditText et;
    private EditText jieguo;
    private String shuru;
    private ImageView translation_title_back;
    private JSONObject obj;
    private Button left_clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.left_translation);
        translation_title_back = (ImageView) findViewById(R.id.translation_title_back);
        translation_title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getViews();//获得控件
    }

    protected void setShuJu() throws JSONException {//最后显示数据的那个地方
        // TODO Auto-generated method stub
        org.json.JSONArray obja = obj.getJSONArray("translation");//收成了   数组对象了

        for (int i = 0; i < obja.length(); i++) {
            jieguo.setText(obja.getString(i));
        }
    }

    /**
     * 获得本窗口里面的所有控件
     */
    private void getViews() {
        et = (android.widget.EditText) findViewById(R.id.left_transedittext1);//输入文字的那个东西
        jieguo = (EditText) findViewById(R.id.left_transedittext2);
        left_clear = (Button) findViewById(R.id.left_clear);
        left_clear.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                et.setText("");
                jieguo.setText("");
            }
        });

    }

    public void doClick(View view) {//点击了那个按钮（翻译的那个按钮）

        jieguo.setText("");
        shuru = et.getText().toString().trim();//获得要翻译的数据
        shuru = java.net.URLEncoder.encode(shuru);//实现编码格式的转化


        if (android.text.TextUtils.isEmpty(shuru)) {

            et.setError("请输入内容");
            return;
        }

        new Thread(new Runnable() {//开启一个子线程去  加载数据

            @Override
            public void run() {
                // TODO Auto-generated method stub
                DiaoYong();//请求服务器的方法
            }
        }).start();

        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 向服务器发送请求的  并且接受返回值的方法
     */
    private void DiaoYong() {

        try {

            obj = new JSONObject(readParse("http://fanyi.youdao.com/openapi.do?keyfrom=123zxcvbnm&key=1903183198&type=data&doctype=json&version=1.1&q=" + shuru));
            handler.sendEmptyMessage(JIAZAI_OK);//发送一个消息  表示加载成功了
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            android.util.Log.e("TAG", "查询失败1");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            android.util.Log.e("TAG", "查询失败2");
            e.printStackTrace();
        }


    }

    //------------------

    public static String readParse(String urlPath) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        URL url = new URL(urlPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream inStream = conn.getInputStream();
        while ((len = inStream.read(data)) != -1) {
            outStream.write(data, 0, len);
        }
        inStream.close();
        return new String(outStream.toByteArray());//通过out.Stream.toByteArray获取到写的数据  
    }

}
